package com.bobo.base.network.base;/*
 * Copyright (C) 2020 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */


import android.text.TextUtils;
import android.util.Log;

import com.bobo.base.network.util.KLog;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okio.Buffer;


/**
 * 添加公共参数
 * 公共参数,或者拦截请求 需要么前面的要 后面的几乎没有用到
 */

public class BasicInterceptor implements Interceptor {
    //
    public static String TAG = "LogInterceptor";
    private boolean isLast = false;

    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request oldRequest = chain.request();
        Request.Builder newRequestBuild = null;
        String method = oldRequest.method();
        String postBodyString = "";
        if ("POST".equals(method)) {
            RequestBody oldBody = oldRequest.body();
            if (oldBody instanceof FormBody) {
                FormBody formBody = (FormBody) oldRequest.body();

                FormBody.Builder builder = new FormBody.Builder();
                Map<String, Object> param = new HashMap<>();
                for (int i = 0; i < formBody.size(); i++) {
                    //@FieldMap 注解 Map元素中 key 与 value 皆不能为null,否则会出现NullPointerException
                    if (formBody.value(i) != null) {
                        builder.add(formBody.name(i), formBody.value(i));
                        param.put(formBody.name(i), formBody.value(i));
                    }
                }

                Map<String, Object> resultMap = sortMapByKey(param);    //按Key进行排序
                StringBuffer stringBuffer = new StringBuffer();
                for (String key : resultMap.keySet()) {
                    stringBuffer.append(key);
                    stringBuffer.append("=");
                    stringBuffer.append(resultMap.get(key));
                    stringBuffer.append("&");
                }
                stringBuffer.append("key");
                stringBuffer.append("=");
                String url = oldRequest.url().toString();
//                if (url.contains("api/login/login") || url.contains("api/login/registerBySystem")) {
//                    String aa = SPUtils.getInstance("aa").getString("aa");
//                    String start = aa.substring(0, 5);
//                    String end = aa.substring(aa.length() - 5, aa.length());
//                    String str = start + end;
//                    stringBuffer.append(str);//KennyTest QMA00C1D3A
//                } else {
//                    stringBuffer.append(GetLoginData.aa());//KennyTest QMA00C1D3A
//                }
//
//                String str = MD5Utils.strToMd5By32(stringBuffer.toString()).toUpperCase().substring(0, 8);

                RequestBody requestBody = oldRequest.body();
                if (requestBody != null) {
                    Buffer buffer = new Buffer();
                    requestBody.writeTo(buffer);
                    Charset charset = Charset.forName("UTF-8");
                    MediaType contentType = requestBody.contentType();
                    if (contentType != null) {
                        charset = contentType.charset(charset);
                    }
                }
                FormBody.Builder formBodyBuilder = new FormBody.Builder();
                for (int i = 0; i < formBody.size(); i++) {
                    //@FieldMap 注解 Map元素中 key 与 value 皆不能为null,否则会出现NullPointerException
                    if (formBody.value(i) != null) {
                        formBodyBuilder.add(formBody.name(i), formBody.value(i));
                    }
                }

                //========新的参数=========
                formBodyBuilder.add("sign", "str");//KennyTest  str
                newRequestBuild = oldRequest.newBuilder();
                RequestBody formBody2 = formBodyBuilder.build();
//                postBodyString = bodyToString(oldRequest.body());
                //========新的请求=========
                newRequestBuild.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"),bodyToString(formBody2)));
            } else if (oldBody instanceof MultipartBody) {
                MultipartBody oldBodyMultipart = (MultipartBody) oldBody;
                List<MultipartBody.Part> oldPartList = oldBodyMultipart.parts();
                MultipartBody.Builder builder = new MultipartBody.Builder();
                builder.setType(MultipartBody.FORM);

                Buffer buffer1 = new Buffer();
                oldBodyMultipart.writeTo(buffer1);
                String postParams = buffer1.readUtf8();
//                            System.out.println("postParams-->"+postParams);
                String[] split = postParams.split("\n");
                List<String> names = new ArrayList<>();
                for (String s : split) {
                    if (s.contains("Content-Disposition")) {
                        names.add(s.replace("Content-Disposition: form-data; name=", "").replace("\"", "").replace("\r", ""));
                    }
                }

                Map<String, Object> param = new HashMap<>();
                List<MultipartBody.Part> TempPart = new ArrayList<>();
//                for (MultipartBody.Part  part: oldPartList) {
                for (int i = 0; i < oldPartList.size(); i++) {

                    if (oldPartList.get(i).body() != null) {
                        if (oldPartList.get(i).body().contentType() != null &&
                                TextUtils.equals(oldPartList.get(i).body().contentType().type(), "image")) {
                            TempPart.add(oldPartList.get(i));
                        }
                        RequestBody body1 = oldPartList.get(i).body();
                        if (body1.contentLength() < 100) {
                            Buffer buffer = new Buffer();
                            body1.writeTo(buffer);
                            String value = buffer.readUtf8();
                            //打印 name和value
                            if (names.size() > i) {
                                param.put(names.get(i), value);
                                KLog.i("params========-->" + names.get(i) + " = " + value);
                            }
                        } else {
                            if (names.size() > i) {
                                KLog.i("params-->" + names.get(i));
                            }
                        }


                    }
                }
//                Map<String, Object> resultMap = sortMapByKey(param);    //按Key进行排序
//                StringBuffer stringBuffer = new StringBuffer();
//
//                for (String key : resultMap.keySet()) {
//                    stringBuffer.append(key);
//                    stringBuffer.append("=");
//                    stringBuffer.append(resultMap.get(key));
//                    stringBuffer.append("&");
//                }
//
//                stringBuffer.append("key");
//                stringBuffer.append("=");
//                stringBuffer.append(GetLoginData.aa());
//                String str = stringBuffer.toString().replace("\r", "");
//                String md = MD5Utils.strToMd5By32(str).toUpperCase().substring(0, 8);


//              builder.addPart(oldBody);  //不能用这个方法，因为不知道oldBody的类型，可能是PartMap过来的，也可能是多个Part过来的，所以需要重新逐个加载进去
              /*  builder.addPart(requestBody1);
                builder.addPart(requestBody2);*/

//                final File file = new File(Environment.getExternalStorageDirectory() + "/qimeng/image/" + fileName);
//                RequestBody requestBody2 = RequestBody.create(file,MediaType.parse("image/jpeg"));
//                builder.addPart(requestBody2);
                for (String key : param.keySet()) {
                    builder.addFormDataPart(key.replace("\r", ""), String.valueOf(param.get(key)));
                }

//                builder.addFormDataPart("sign", md);

                for (int i = 0; i < TempPart.size(); i++) {
                    builder.addPart(TempPart.get(i));
                }

                newRequestBuild = oldRequest.newBuilder();
                newRequestBuild.post(builder.build());
                Log.e(TAG, "MultipartBody," + oldRequest.url());
            } else {
                newRequestBuild = oldRequest.newBuilder();
            }
        } else {

            String _time = String.valueOf(System.currentTimeMillis() / 1000);
            // 添加新的参数
            HttpUrl.Builder commonParamsUrlBuilder = oldRequest.url()
                    .newBuilder()
                    .scheme(oldRequest.url().scheme())
                    .host(oldRequest.url().host())
                    .addQueryParameter("_time", _time);
//                    .addQueryParameter("sign", MD5.getMessageDigest(new StringBuilder().append(_time).append(
//                            Constant.KEY).toString()))
//                    .addQueryParameter("only_token", GetLoginData.getOnlyToken());
            newRequestBuild = oldRequest.newBuilder()
                    .method(oldRequest.method(), oldRequest.body())
                    .url(commonParamsUrlBuilder.build());
        }
        Request newRequest = newRequestBuild
                .addHeader("Accept", "application/json")
                .addHeader("Accept-Language", "zh")
                .build();

        long startTime = System.currentTimeMillis();
        okhttp3.Response response = chain.proceed(newRequest);
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        MediaType mediaType = response.body().contentType();
        String content = response.body().string();
        int httpStatus = response.code();
        StringBuilder logSB = new StringBuilder();

        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, content))
                .build();
    }

    private static String bodyToString(final RequestBody request) {
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if (copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }

    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map<String, Object> sortMap = new TreeMap<String, Object>(new MapKeyComparator());

        sortMap.putAll(map);

        return sortMap;

    }

    static class MapKeyComparator implements Comparator<String> {

        @Override
        public int compare(String str1, String str2) {

            return str1.compareTo(str2);
        }
    }
}